import { getTableList } from '@/api';
import { getApiConfig } from '@/config/api-config';
import { getTableBodyHeight } from '@/utils';
import { useRequest, useSize } from 'ahooks';
import { Button, Table } from 'antd';
import { ComponentRef, useRef } from 'react';
import { useModel } from 'umi';

type TableRef = ComponentRef<typeof Table>;
export function ThirdPartyTableList() {
  const {
    setTableId,
    mainTableId: mainTableId,
    setMainTable,
  } = useModel('fieldConfig');
  const ref = useRef<TableRef>(null);
  const size = useSize(ref.current?.nativeElement);
  const tableBodyHeight =
    size && getTableBodyHeight(size.height, { hasFooter: false });
  const { data } = useRequest(() =>
    getTableList({ space_id: getApiConfig()?.spaceId }),
  );
  // console.log(data);
  const tableData = data?.tables.map((item) => {
    return {
      id: item.table_id,
      name: item.name,
    };
  });

  return (
    <Table
      pagination={false}
      rowKey={'id'}
      rowSelection={{
        type: 'radio',
        onChange(selectedRowKeys, selectedRows, info) {
          // console.log({ selectedRowKeys, selectedRows, info });
        },
        onSelect(record) {
          console.log(record);
          setTableId(record.id);
        },
      }}
      ref={ref}
      className="overflow-auto"
      scroll={{ y: tableBodyHeight }}
      columns={[
        {
          title: '表名',
          dataIndex: 'name',
        },
        {
          title: '表ID',
          dataIndex: 'id',
        },
        {
          title: '主表',
          dataIndex: 'isMainTable',
          render(_, record) {
            if (mainTableId === record.id) {
              return 'true';
            }
          },
        },
        {
          title: '操作',
          render(_, record) {
            return (
              <Button type="primary" onClick={() => setMainTable(record.id)}>
                设为主表
              </Button>
            );
          },
        },
      ]}
      dataSource={tableData}
    ></Table>
  );
}
